package com.ruoyi.work.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.work.domain.WorkStage;
import com.ruoyi.work.mapper.WorkStageMapper;
import com.ruoyi.work.service.IWorkStageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: MMDZ
 * @Desc:
 */
@Service
public class WorkStageServiceImpl implements IWorkStageService {

    @Autowired
    private WorkStageMapper stageMapper;

    /**
     * 查询所有阶段列表 - 条件
     *
     * @param stage
     * @return
     */
    @Override
    public List<WorkStage> selectStageList(WorkStage stage) {
        return stageMapper.selectStageList(stage);
    }

    /**
     * 查询所有阶段列表 - 作选择框
     *
     * @return
     */
    @Override
    public List<WorkStage> selectStageAll() {
        return stageMapper.selectStageAll();
    }

    /**
     * 根据id查询阶段详情
     *
     * @param stageId
     * @return
     */
    @Override
    public WorkStage selectStageById(Long stageId) {
        return stageMapper.selectStageById(stageId);
    }

    /**
     * 阶段名称是否重复
     *
     * @param stage
     * @return
     */
    @Override
    public String checkStageNameUnique(WorkStage stage) {
        Long stageId = StringUtils.isNull(stage.getStageId()) ? -1L : stage.getStageId();
        WorkStage info = stageMapper.checkStageNameUnique(stage.getStageName());
        if (StringUtils.isNotNull(info) && info.getStageId().longValue() != stageId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 新增
     *
     * @param workStage
     * @return
     */
    @Override
    public int insertStage(WorkStage workStage) {
        return stageMapper.insertStage(workStage);
    }

    /**
     * 修改
     *
     * @param workStage
     * @return
     */
    @Override
    public int updateStage(WorkStage workStage) {
        return stageMapper.updateStage(workStage);
    }

    /**
     * 删除
     *
     * @param stageIds
     * @return
     */
    @Override
    public int deleteStageByIds(Long[] stageIds) {
        for (Long stageId : stageIds) {
            WorkStage stage = selectStageById(stageId);
            if (countProjectStageById(stageId) > 0) {
                throw new ServiceException(String.format("%1$s已分配,不能删除", stage.getStageName()));
            }
        }
        return stageMapper.deleteStageByIds(stageIds);
    }

    /**
     * 通过阶段ID查询项目使用数量
     *
     * @param stageId 阶段ID
     * @return 结果
     */
    @Override
    public int countProjectStageById(Long stageId) {
        return stageMapper.countProjectStageById(stageId);
    }

}
